﻿using Microsoft.Extensions.Caching.Distributed;
using System;
using System.Text;

namespace Enter.Utils.CacheExt
{
    public static class DistributedCacheExtend
    {
        public static void Set<T>(this IDistributedCache cache, string key, T value)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                key = typeof(T).Name;
            }
            // new DistributedCacheEntryOptions().SetSlidingExpiration(Settings.CacheTimeExpiration)
            cache.SetString(key, JsonExtend.Serialize(value), new DistributedCacheEntryOptions().SetAbsoluteExpiration(Settings.CacheTimeExpiration));
        }

        public static void Set<T>(this IDistributedCache cache, T value)
        {
            cache.Set<T>(typeof(T).Name, value);
        }

        public static T Get<T>(this IDistributedCache cache, string key = "")
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                key = typeof(T).Name;
            }
            var value = cache.GetString(key);
            return value == null ? default : JsonExtend.Deserialize<T>(value);
        }

        public static void Remove<T>(this IDistributedCache cache)
        {
            cache.Remove(typeof(T).Name);
        }
    }
}
